#!/bin/bash - 
#
#  Usage:     Calculation PI by "Monte Carlo" by Medel Cooper
#  Author:    bucunzai <freecityer@gmail.com>
#  Version:   1.0
#  Created:   03/09/2011 03:27:10 PM CST
#

set -o nounset                              # Treat unset variables as an error

DIMESION=10000
MAXSHOTS=1000
Pmultilier=4.0
declare -r M_PI=3.141592654

get_random(){
    SEED=$(head -n 1 /dev/urandom | od -N 1 | awk '{ print $2 }')
    RANDOM=$SEED
    let "rnum = $RANDOM % $DIMESION"
    echo $rnum
}

distance=
hypotenuse(){
distance=$(bc -l << EOF
scale=0
sqrt( $1*$1 + $2*$2 )
EOF
)
}

# Main()
# Initialize variables
shots=0
splashes=0
thuds=0
Pi=0
error=0

while [ "$shots" -lt "$MAXSHOTS" ]
do
    xCoord=$(get_random)
    yCoord=$(get_random)
    hypotenuse $xCoord $yCoord

    ((shots++))
    printf "#%4d   " $shots
    printf "Xc = %4d  " $xCoord
    printf "Yc = %4d  " $yCoord
    printf "Distance = %5d  " $distance

    if [ "$distance" -le "$DIMESION" ]
    then
        echo -n "SPLASH!   "
        ((splashes++))
    else
        echo -n "THUD!     "
        ((thuds++))
    fi

    Pi=$(echo "scale=9; $Pmultilier*$splashes/$shots" | bc)
    echo -n "PI ~ $Pi"
    echo
done

echo
echo "After $shots shots, PI looks like approximately $Pi."
echo
exit 0
